import moment from "moment";
import tools from "@/util/tools";
import { getCompanyInfo } from "@/util/auth";
import instance from "@/main";
import globalSite from "@/config/globalSite";
import {
  checkOrderDetail,
  checkLineOrderDetail,
  getMessageSwitchStatus
} from "./message";
import { isPricing, isConfirm } from "./order";

// 查找父级
export function getParent(list, childId) {
  let arrRes = [];
  if (list.length == 0) {
    if (childId) {
      arrRes.unshift(list);
    }
    return arrRes;
  }
  let rev = (data, nodeId) => {
    for (let i = 0, length = data.length; i < length; i++) {
      let node = data[i];
      if (node.id == nodeId) {
        arrRes.unshift(node);
        rev(list, node.webParentId);
        break;
      } else {
        if (node.children) {
          rev(node.children, nodeId);
        }
      }
    }
    return arrRes;
  };
  arrRes = rev(list, childId);
  return arrRes;
}

// 根据路由查找菜单列表
export function findRouteMenu(data, routerName) {
  let menuName = {};

  function findMenu(list) {
    for (let i = 0; i < list.length; i++) {
      if (list[i].name === routerName) {
        menuName = {
          ...list[i]
        };
        break;
      } else if (list[i].children) {
        findMenu(list[i].children);
      }
    }
    return menuName;
  }
  return findMenu(data);
}

// 转树
export function toTree(list, parId, option) {
  let data = JSON.parse(JSON.stringify(list));
  let cId = option ? option.id : "id";
  let pId = option ? option.parentId : "parentId";
  let len = data.length;

  function loop(parId) {
    let res = [];
    for (let i = 0; i < len; i++) {
      let item = data[i];
      if (item[pId] === parId) {
        item.children = loop(item[cId]);
        if (item.children.length === 0) delete item.children;
        res.push(item);
      }
    }
    return res;
  }
  return loop(parId);
}

// 反转树
export function invertTree(data) {
  let res = [];
  let arr = JSON.parse(JSON.stringify(data));
  let findChildName = list => {
    list.forEach(item => {
      if (item.children) {
        findChildName(item.children);
        delete item.children;
        res.push(item);
      } else {
        res.push(item);
      }
    });
  };
  findChildName(arr);
  return res;
}

// 防抖
export function debounce(fn, time) {
  let delay = time || 200;
  let timer;
  return function() {
    let th = this;
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function() {
      timer = null;
      fn.apply(th, args);
    }, delay);
  };
}

// 节流
export function throttle(fn, time) {
  let last;
  let timer;
  let interval = time || 200;
  return function() {
    let th = this;
    let args = arguments;
    let now = +new Date();
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout(function() {
        last = now;
        fn.apply(th, args);
      }, interval);
    } else {
      last = now;
      fn.apply(th, args);
    }
  };
}

// 查询枚举值
export function getEnum(data, val, type) {
  let v = type ? "desc" : "value";
  let d = type ? "value" : "desc";
  let res = "";
  for (const key in data) {
    if (data[key][v] === tools.toInt(val)) {
      res = data[key][d];
    }
  }
  return res;
}

// 获取随机数
export function random(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

// 根据品种id获取完整层级
export function getCategoryId(val, option = {}) {
  /*
    @ option 配置项
    @ key: String 用于查找的key，默认categoryCode
    @ value: String 返回值对应的key，默认categoryName
    @ obj: Boolean 是否返回对象数组，默认返回字符串数组
    @ level: Array 返回的层级，默认返回一级三级
  */
  const code = option.key ? option.key : "id";
  const value = option.value ? option.value : "id";
  let categoryList = JSON.parse(sessionStorage.getItem("category"));
  let level = categoryList.filter(i => i[code] === val);
  let pLevel = categoryList.filter(i => i.id === level[0].categoryType);
  let res = [pLevel[0][value], level[0][value]];
  return res;
}

// 延时执行
export function delay(fn, delayTime) {
  /**
  @ fn: 需要延时操作方法
  @ delayTime:延时时间(毫秒)
  */
  var delayIndex = setTimeout(function() {
    fn();
    clearTimeout(delayIndex);
  }, delayTime);
}

// 时间戳转换时间
export function getTime(val, format) {
  let f = format || "YYYY-MM-DD HH:mm:ss";
  return val ? moment(val).format(f) : "";
}
// 时间转换时间戳
export function timeToTimestamp(val, num) {
  if (num) return moment(val).unix(); //10位
  return moment(val).valueOf(); //13位
}

// 是否相同公司
export function sameCompany(val) {
  let companyInfo = getCompanyInfo();
  return companyInfo.id === val;
}

//获取当前买卖家身份 1买家 2卖家
export function getCurIdentity() {
  let routeName = instance.$route.name;
  let res = routeName.substring(0, 5) === "buyer" ? (res = 1) : (res = 2);
  return res;
}

// 是否在卖家中心
export function isSeller() {
  let res = getCurIdentity() === 2;
  return res;
}

// 是否在买家中心
export function isBuyer() {
  let res = getCurIdentity() === 1;
  return res;
}

// 是否禁止登录，在同一浏览器有一个标签页登录时，其他标签页禁止登录
export function loginDisable() {
  let disableLogin = sessionStorage.getItem("disableLogin");
  let loginPhone = localStorage.getItem("loginPhone");
  let res;
  // 是否存在禁止登录标识
  if (disableLogin) {
    // 存在loginPhone说明已有标签页登录了，则当前标签页禁止登录
    if (loginPhone) {
      res = true;
    } else {
      sessionStorage.removeItem("disableLogin");
      res = false;
    }
  } else {
    res = false;
  }
  return res;
}

// 下载流文件
export function downloadFile(res) {
  instance.$message.warning("正在导出文件，请耐心等待");
  const link = document.createElement("a");
  let blob = new Blob([res.data], { type: res.data.type });
  link.style.display = "none";
  link.href = URL.createObjectURL(blob);
  link.setAttribute(
    "download",
    decodeURIComponent(
      res.headers["content-disposition"].split(";")[1].split("=")[1]
    )
  );
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

//验证合同章弹窗
/*
  @ res: 请求返回的res
 */
export function verificationSealPopover(res) {
  let code = res.code;
  let errorCode = globalSite.errorCode;
  let popupContent = res.msg;
  let routeName;
  let confirmButtonText = "去上传";
  let tips = () => {
    instance.$info({
      title: "温馨提示",
      content: popupContent,
      okText: confirmButtonText,
      cancelText: "取消",
      onOk() {
        if (routeName) {
          instance.$router.push({ name: routeName });
        }
      }
    });
  };
  if (code == errorCode.noContractSeal) {
    // 合同章
    routeName = "contractSeal";
  } else if (code == errorCode.contractSealAudit) {
    // 合同章审核中
    confirmButtonText = "";
  } else if (code == errorCode.noCorporateSeal) {
    // 法人章
    routeName = "corporatePersonalSeal";
  } else if (code == errorCode.corporateAudit) {
    // 法人章审核中
    confirmButtonText = "";
  } else if (code == errorCode.signedAccountError) {
    //企业未创建签署账号
    confirmButtonText = "去创建";
    routeName = "certificateCA";
  } else {
    confirmButtonText = "知道了";
  }
  tips();
}

// 是否线路订单
export function isLine() {
  let paths = instance.$route.path.split("/");
  return paths.indexOf("line") !== -1;
}

export {
  checkOrderDetail,
  checkLineOrderDetail,
  getMessageSwitchStatus,
  isConfirm,
  isPricing
};
